import React, { useEffect, useState, useRef, useCallback, memo, useMemo } from 'react'
import Taro from '@tarojs/taro'
import { Text, View, ScrollView, PageContainer, Image, CoverView, RichText } from '@tarojs/components'
import { getNavTop, getFullSrcs } from '@/utils/Helper'
import NavCustomBar from '@/components/NavBar'
import towxml from '@/components/towxml'
import { NavBarHomeLeft } from '@/components/NavBar/NavBarTitle'
import BottomBtn from './bottomBtn/index'

import DefaultDiv from './defaultDiv/index'
import PopFeedback from './popFeedback/index'
import DrawerContent from './drawerContent/index'
import { handleTree, extractTree, generateUniqueId } from './utils/index'
import { listForCustomer, insertAPI, isSatisfiedAPI } from './utils/request'
import styles from './index.module.scss'

export default function IndexPage() {
  const [list, setList] = useState<any[]>([])

  const [scrollHeight, setScrollHeight] = useState<any>('73vh ')
  const [bottom, setBottom] = useState<any>('0')
  const [toView, setToView] = useState<any>('')
  const [scrollTop, setScrollTop] = useState<any>('')
  const SocketTask = useRef<any>(null)
  const phoneNumber = useRef<any>('15938313592')
  // const [bottomHorizontal, setBottomHorizontal] = useState<any>('121rpx')
  // const innerAudioContext = useRef<any>(Taro.createInnerAudioContext())
  const [timeOver, setTimeOver] = useState(false)
  const [webSearch, setWebSearch] = useState(false)
  //反馈弹窗的状态
  const popRef = useRef<any>(null)
  const drawerRef = useRef<any>(null)
  //设置会话id
  const sessionId = useRef<any>(null)
  //获取最后一项的id
  // const [lastContent, setLastContent] = useState<any>({})
  const lastContent = useRef<any>({})
  // const [sessionId, setSessionId] = useState(null)
  //记录按下的位置坐标
  let startY = useRef(0)
  //记录上或者下滑的状态
  let directionState = useRef('down')
  //是否触底
  const [isBottom, setIsBottom] = useState(false)
  useEffect(() => {
    return () => {
      if (SocketTask.current) {
        SocketTask.current.close()
        SocketTask.current = null
      }
    }
  }, [])

  // 添加处理点赞和踩的函数
  const handleFeedback = (type, e, item) => {
    let formData = new FormData()
    console.log(item, 'itemitemitem')
    e.stopPropagation() // 阻止事件冒泡

    if (type === 'up') {
      if (item.isSatisfied === true) {
        formData.append('id', item.message_id)
        let data = formData.getData()
        isSatisfiedAPI({
          method: 'POST',
          header: {
            'content-type': data.contentType
          },
          url: `/chat/isSatisfied`,
          data: data.buffer
        }).then((res) => {
          if (res.code === 200) {
            setList((prevList) => {
              let flatprevList = [...prevList]
              let lindex = flatprevList.findIndex((fitem) => {
                return fitem.message_id === item.message_id
              })
              flatprevList[lindex] = {
                ...flatprevList[lindex],
                isSatisfied: null
              }
              return flatprevList
            })
          }
        })
      } else {
        formData.append('id', item.message_id)
        formData.append('isSatisfied', true)
        let data = formData.getData()
        isSatisfiedAPI({
          method: 'POST',
          header: {
            'content-type': data.contentType
          },
          url: `/chat/isSatisfied`,
          data: data.buffer
        }).then((res) => {
          if (res.code === 200) {
            setList((prevList) => {
              let flatprevList = [...prevList]
              let lindex = flatprevList.findIndex((fitem) => {
                return fitem.message_id === item.message_id
              })
              flatprevList[lindex] = {
                ...flatprevList[lindex],
                isSatisfied: true
              }
              return flatprevList
            })
          }
        })
      }
    } else {
      if (item.isSatisfied === false) {
        formData.append('id', item.message_id)
        let data = formData.getData()
        isSatisfiedAPI({
          method: 'POST',
          header: {
            'content-type': data.contentType
          },
          url: `/chat/isSatisfied`,
          data: data.buffer
        }).then((res) => {
          if (res.code === 200) {
            setList((prevList) => {
              let flatprevList = [...prevList]
              let lindex = flatprevList.findIndex((fitem) => {
                return fitem.message_id === item.message_id
              })
              flatprevList[lindex] = {
                ...flatprevList[lindex],
                isSatisfied: null
              }
              return flatprevList
            })
          }
        })
      } else {
        popRef.current.open(item)
      }
    }
  }
  const submitFun = (item) => {
    const FormData = require('./utils/formData.js')
    let formData = new FormData()
    formData.append('id', item.message_id)
    formData.append('isSatisfied', false)
    formData.append('feedbackType', item.feedbackType)
    formData.append('feedback', item.feedback)
    let data = formData.getData()
    isSatisfiedAPI({
      method: 'POST',
      header: {
        'content-type': data.contentType
      },
      url: `/chat/isSatisfied`,
      data: data.buffer
    }).then((res) => {
      if (res.code === 200) {
        setList((prevList) => {
          let flatprevList = [...prevList]
          let lindex = flatprevList.findIndex((fitem) => {
            return fitem.message_id === item.message_id
          })
          flatprevList[lindex] = {
            ...flatprevList[lindex],
            isSatisfied: false
          }
          return flatprevList
        })
        popRef.current.close()
      }
    })
  }
  const handleCopy = (text, e) => {
    console.log(text, 'handleCopyhandleCopyhandleCopy')

    e.stopPropagation() // 阻止事件冒泡，防止触发外层的 onClick
    Taro.setClipboardData({
      data: text,
      success: function() {
        Taro.showToast({
          title: '复制成功',
          icon: 'none',
          duration: 1500
        })
      },
      fail: function() {
        Taro.showToast({
          title: '复制失败',
          icon: 'none',
          duration: 1500
        })
      }
    })
  }
  const changeHeight = useCallback(
    async (height: number, key: string) => {
      if (key === 'touchBottom') {
        // 等待内容渲染
        await new Promise((resolve) => setTimeout(resolve, 100))
        var query = Taro.createSelectorQuery()
        query
          .selectAll('#msg-box')
          .boundingClientRect((rects: any) => {
            if (!rects || !rects.length) return
            // 计算总高度
            const totalHeight = rects.reduce((sum, rect) => sum + rect.height, 0)
            console.log(totalHeight, 'totalHeighttotalHeighttotalHeight')
            // 设置滚动位置
            setScrollTop(totalHeight)
          })
          .exec(function(res) {})
      } else {
        //设置键盘高度
        if (typeof height === 'number') {
          setScrollHeight('calc(73vh  - ' + height + 'px' + ')')
          setBottom(height + 'px')
          setToView(`msg-${list.length - 1}`)
        } else {
          setScrollHeight('73vh ')
          setBottom('0')
          setToView(`msg-${list.length}`)
        }
      }
    },
    [list]
  )

  const emitDataList = useCallback(
    async (videoItem: any) => {
      setTimeOver(true)
      const startTime = Date.now()
      let prevList1 = [...list]
      // let flatprevList1 = extractTree(prevList1)
      if (prevList1.length === 0) {
        await insertAPI({ title: videoItem.content, phoneNumber: phoneNumber.current }).then((res) => {
          sessionId.current = res.data
        })
      }
      // 放入问题
      prevList1.push({
        ...videoItem,
        pageNo: 1,
        message_id: generateUniqueId(),
        parent_id: null
      })
      //放入思考
      prevList1.push({
        content: '',
        thinking_enabled: true,
        thinking_content: '',
        role: 'ASSISTANT',
        thinking_elapsed_secs: 0,
        message_id: generateUniqueId(),
        parent_id: prevList1[prevList1.length - 1].message_id,
        isLast: true
      })

      setList(prevList1)
      SocketTask.current = await Taro.connectSocket({
        url: 'wss://jn-ai-test-api.jingxizhigu.cn/ws/chat/' + phoneNumber.current,
        //   url: 'wss://testds.jingxizhigu.cn:11027/v1/chat/completions',
        success: function(res) {
          console.log(res)
        },
        fail: function(err) {
          console.log(err)
        }
      })
      await SocketTask.current.onOpen((res) => {
        SocketTask.current.send({
          //向服务器发送消息
          data: JSON.stringify({
            model: 'DeepSeek-R1',
            messages: [
              {
                role: 'user',
                content: videoItem.content
              }
            ],
            presence_penalty: 0.5,
            frequency_penalty: 0,
            seed: null,
            temperature: 0.1,
            // top_p: 0.95,
            stream: true,
            phoneNumber: phoneNumber.current,
            web_search: webSearch,
            sessionId: sessionId.current
          }),
          success: function(res1) {
            console.log(res1, '发送成功了')
          },
          fail: function(err) {
            console.log(err, '发送失败了')
          }
        })
      })
      let accumulatedText = ''
      let analysisText = ''
      let thinkTimeFlag = true
      let pending = false
      SocketTask.current.onMessage((res) => {
        if (res.data.includes('data:')) {
          let cleanedContent = res.data.replace('data: ', '')
          try {
            const dataObj = JSON.parse(cleanedContent)
            const content = dataObj.choices[0]?.delta?.content

            if (content) {
              // 处理特殊标记
              if (content === '<think>') {
                setList((prevList) => {
                  let flatprevList = [...prevList]
                  let lindex = flatprevList.findIndex((item) => {
                    return item.isLast
                  })
                  flatprevList[lindex] = {
                    ...flatprevList[lindex],
                    thinking_enabled: true
                  }
                  return flatprevList
                })
                thinkTimeFlag = true
              } else if (content === '</think>') {
                setList((prevList) => {
                  let flatprevList = [...prevList]
                  let lindex = flatprevList.findIndex((item) => {
                    return item.isLast
                  })
                  flatprevList[lindex] = {
                    ...flatprevList[lindex],
                    thinking_enabled: false,
                    thinking_elapsed_secs: Math.floor((Date.now() - startTime) / 1000)
                  }
                  return flatprevList
                })
                thinkTimeFlag = false
              } else {
                if (thinkTimeFlag) {
                  analysisText += content.replace(/(\r\n|\n|\r)/gm, '<br/>')
                } else {
                  accumulatedText += content
                }
              }
            }
            //判断是否上滑还是下滑 下滑触底
            // if (directionState.current === 'down') {
            // changeHeight(0, 'touchBottom')
            // }

            if (!pending) {
              pending = true
              setTimeout(() => {
                setList((prevList) => {
                  let flatprevList = [...prevList]
                  let lindex = flatprevList.findIndex((item) => {
                    return item.isLast
                  })
                  flatprevList[lindex] = {
                    ...flatprevList[lindex],
                    content: accumulatedText,
                    thinking_content: analysisText
                  }
                  return flatprevList
                })
                pending = false
              }, 100)
            }

            if (cleanedContent === '[DONE]') {
              setTimeOver(false)
            }
          } catch (error) {
            console.log('error', error)
            setTimeOver(false)
          }
        } else if (res.data.includes('message: ')) {
          let cleanedContent = res.data.replace('message: ', '')
          try {
            const dataObj = JSON.parse(cleanedContent)
            setList((prevList) => {
              let flatprevList = [...prevList]
              let lindex = flatprevList.findIndex((item) => {
                return item.isLast
              })
              if (flatprevList.length === 2) {
                flatprevList[0].message_id = dataObj._id
                flatprevList[0].chatId = dataObj.chatId
                flatprevList[1].parent_id = dataObj._id
              } else {
                flatprevList[lindex - 1].message_id = dataObj._id
                flatprevList[lindex - 1].chatId = dataObj.chatId
                flatprevList[lindex].parent_id = dataObj._id
              }
              return flatprevList
            })
          } catch (error) {
            SocketTask.current.close()
            setList((prevList) => {
              let flatprevList = [...prevList]
              let lindex = flatprevList.findIndex((item) => {
                return item.isLast
              })
              flatprevList[lindex].message_id = cleanedContent
              flatprevList[lindex].isLast = false

              return flatprevList
            })
          }
        }
      })
    },
    [list, changeHeight, lastContent, webSearch]
  )
  // const audioPlay = (src: string) => {
  //   if (src) {
  //     innerAudioContext.current.src = src
  //     innerAudioContext.current.play()
  //   }
  // }

  const changePhotosHeight = (height: number) => {
    setScrollHeight('calc(73vh  - ' + height + 'px' + ')')
  }
  const btnFun = useCallback((type, flag) => {
    if (type === 'webSearch') {
      setWebSearch(flag)
    }
  }, [])
  const newChatFun = useCallback(() => {
    if (!timeOver) {
      if (SocketTask.current) SocketTask.current.close()
      setList([])
      sessionId.current = null
      lastContent.current = {}
    }
  }, [timeOver])

  // 更新问答列表
  const refreshData = useCallback(
    async (chatItem, fatherItem) => {
      console.log(chatItem, fatherItem, 'chatItem, fatherItemchatItem, fatherItem')
      let listData = [...list]
      listData[
        listData.findIndex((fitem, findex) => {
          return fitem.message_id === fatherItem.message_id
        })
      ].pageNo = fatherItem.pageNo + 1
      listData.push({
        content: '',
        thinking_enabled: true,
        thinking_content: '',
        role: 'ASSISTANT',
        thinking_elapsed_secs: 0,
        message_id: generateUniqueId(),
        parent_id: chatItem.parent_id,
        isLast: true
      })
      setList(listData)
      setTimeOver(true)
      const startTime = Date.now()
      SocketTask.current = await Taro.connectSocket({
        url: 'wss://jn-ai-test-api.jingxizhigu.cn/ws/chat/' + phoneNumber.current,
        //   url: 'wss://testds.jingxizhigu.cn:11027/v1/chat/completions',
        success: function(res) {
          console.log(res)
        },
        fail: function(err) {
          console.log(err)
        }
      })

      SocketTask.current.onOpen((res) => {
        SocketTask.current.send({
          //向服务器发送消息
          data: JSON.stringify({
            model: 'DeepSeek-R1',
            messages: [
              {
                role: 'user',
                content: fatherItem.content
              }
            ],
            presence_penalty: 0.5,
            frequency_penalty: 0,
            seed: null,
            temperature: 0.1,
            // top_p: 0.95,
            stream: true,
            phoneNumber: phoneNumber.current,
            web_search: webSearch,
            parentId: chatItem.parent_id,
            sessionId: sessionId.current,
            chatId: fatherItem.chatId
          }),
          success: function(res1) {
            console.log(res1, '发送成功了')
          },
          fail: function(err) {
            console.log(err, '发送失败了')
          }
        })
      })
      let accumulatedText = ''
      let analysisText = ''
      let thinkTimeFlag = true
      SocketTask.current.onMessage((res) => {
        if (res.data.includes('data: ')) {
          let cleanedContent = res.data.replace('data: ', '')
          try {
            const dataObj = JSON.parse(cleanedContent)
            const content = dataObj.choices[0]?.delta?.content

            if (content) {
              // 处理特殊标记
              if (content === '<think>') {
                setList((prevList) => {
                  let flatprevList = [...prevList]

                  let lindex = flatprevList.findIndex((item) => {
                    return item.isLast
                  })
                  flatprevList[lindex] = {
                    ...flatprevList[lindex],
                    thinking_enabled: true
                  }
                  return flatprevList
                })

                thinkTimeFlag = true
              } else if (content === '</think>') {
                setList((prevList) => {
                  let flatprevList = [...prevList]
                  let lindex = flatprevList.findIndex((item) => {
                    return item.isLast
                  })
                  flatprevList[lindex] = {
                    ...flatprevList[lindex],
                    thinking_enabled: false,
                    thinking_elapsed_secs: Math.floor((Date.now() - startTime) / 1000)
                  }
                  return flatprevList
                })
                thinkTimeFlag = false
              } else {
                if (thinkTimeFlag) {
                  analysisText += content.replace(/(\r\n|\n|\r)/gm, '<br/>')
                } else {
                  accumulatedText += content
                }
              }
            }
            //判断是否上滑还是下滑 下滑触底
            // if (directionState.current === 'down') {
            // changeHeight(0, 'touchBottom')
            // }

            setList((prevList) => {
              let flatprevList = [...prevList]
              let lindex = flatprevList.findIndex((item) => {
                return item.isLast
              })
              flatprevList[lindex] = {
                ...flatprevList[lindex],
                content: accumulatedText,
                thinking_content: analysisText
              }
              return flatprevList
            })

            if (cleanedContent === '[DONE]') setTimeOver(false)
          } catch (error) {
            console.log('error', error)
            setTimeOver(false)
          }
        } else if (res.data.includes('message: ')) {
          let cleanedContent = res.data.replace('message: ', '')
          try {
            const dataObj = JSON.parse(cleanedContent)
            console.log(dataObj, 'messagemessagemessage')
            return
          } catch (error) {
            console.log('catchcatchcatchcatchcatchcatch', error)
            setList((prevList) => {
              let flatprevList = [...prevList]
              let lindex = flatprevList.findIndex((item) => {
                return item.isLast
              })
              flatprevList[lindex] = {
                ...flatprevList[lindex],
                message_id: cleanedContent,
                isLast: false
              }
              return flatprevList
            })
            SocketTask.current.close()
          }
        }
      })
    },
    [list, changeHeight, webSearch]
  )
  // 点击抽屉item
  const clickItem = useCallback((item) => {
    //处理think标签
    function dealWithThinkTag(str) {
      if (!str.includes('<think>')) {
        return ['', str]
      }
      if (typeof str !== 'string') {
        return ['', '']
      }
      let thinkContent = str
        .substring(str.indexOf('<think>') + '<think>'.length, str.indexOf('</think>'))
        .replace(/(\r\n|\n|\r)/gm, '<br/>')
      let outsideContent = str.substring(str.indexOf('</think>') + '</think>'.length, str.length)
      return [thinkContent, outsideContent]
    }
    sessionId.current = item.id
    //调取接口查询历史记录
    listForCustomer({ sessionId: item.id, phoneNumber: phoneNumber.current, pageNo: 1, pageSize: 1000 }).then((res) => {
      let resData = res.data.rows.reverse().map((resitem, resindex) => {
        if (resitem.role === 1) {
          return {
            ...resitem,
            role: 'USER',
            message_id: resitem.id,
            parent_id: resitem.parentId,
            thinking_enabled: false,
            pageNo: 1
          }
        } else {
          return {
            ...resitem,
            role: 'ASSISTANT',
            message_id: resitem.id,
            parent_id: resitem.parentId,
            thinking_enabled: false,
            thinking_content: dealWithThinkTag(resitem.content)[0],
            content: dealWithThinkTag(resitem.content)[1],
            thinking_elapsed_secs: Math.floor(resitem.thinkDuration / 1000)
          }
        }
      })
      setTimeOver(false)
      setList(resData)

      drawerRef.current.close()
    })
    console.log(item)
  }, [])
  //删除放法
  const delConfirm = useCallback(
    (id) => {
      if (sessionId.current === id) {
        newChatFun()
      }
    },
    [newChatFun]
  )
  // 监听touchstart事件
  function handleTouchStart(e) {
    // startY.current = e.touches[0].clientY
    console.log('handleTouchStarthandleTouchStart', e.touches[0].clientY)
    setIsBottom(true)
    // setScrollTop(e.touches[0].clientY)
  }

  // 监听touchmove事件
  function handleTouchMove(e) {
    // const moveY = e.touches[0].clientY
    // const direction = moveY > startY.current ? 'up' : 'down'
    // console.log(`用户正在向${direction}滑动`)
    // directionState.current = direction
    setIsBottom(true)
  }

  // 监听touchend事件
  function handleTouchEnd(e) {
    // const moveY = e.changedTouches[0].clientY
    // const direction = moveY > startY.current ? 'up' : 'down'
    // console.log(`用户向${direction}滑动结束`)
    // directionState.current = direction
    setIsBottom(true)
  }

  const onScrollToLower = () => {
    console.log(213123123, '触底触底触底触底')
    setIsBottom(false)
    changeHeight(0, 'touchBottom')
    setToView('msg_last1')
  }
  const toBottom = () => {
    console.log('toBottomtoBottomtoBottom')
    // changeHeight(0, 'touchBottom')
    setToView('msg_last')
  }
  console.log(123123213123123123)
  const treeData = useMemo(() => {
    return handleTree(list)
  }, [list])
  return (
    <View className={styles['input-container']}>
      <NavCustomBar
        backNode={NavBarHomeLeft()}
        title={
          <CoverView style={{ textAlign: 'center' }}>
            {/* <CoverView>智能客服</CoverView>
            <CoverView style={{ fontSize: '24rpx', color: '#666', marginTop: '4rpx' }}>
              Powered by DeepSeek-R1
            </CoverView> */}
            中优 Agent
          </CoverView>
        }
      />
      <View
        className={styles['chat_content']}
        style={{ paddingTop: `${getNavTop()}px`, height: `calc(100vh - ${getNavTop()}px)` }}
      >
        <View className={styles['top_content']}>
          <Image
            src={getFullSrcs('documents/history.jpg')}
            onClick={() => {
              drawerRef.current.open()
            }}
          ></Image>
          <View></View>
          <Image src={getFullSrcs('documents/plus.jpg')} onClick={newChatFun}></Image>
        </View>
        <ScrollView
          scrollY
          style={{ height: scrollHeight }}
          scrollIntoView={toView}
          className={styles['scrollView_style']}
          scrollTop={scrollTop}
          id='scrollView'
          onScrollToLower={onScrollToLower}
          onTouchstart={handleTouchStart}
          onTouchend={handleTouchEnd}
          onTouchMove={handleTouchMove}
          lowerThreshold={30}
        >
          {list[0]?.content ? (
            ''
          ) : (
            <View className={styles['input_defaultDiv']}>
              <DefaultDiv></DefaultDiv>
            </View>
          )}
          {treeData.map((item, index) => {
            return (
              <View className={styles['chat-item']} key={index}>
                {/* 问题 */}
                <View className={styles['chat-item-ask']} id='msg-box'>
                  <View className={styles['img_list']}>
                    {item.files?.map((fitem, findex) => {
                      return (
                        <View className={styles['img_list_item']} key={findex}>
                          <Image src={getFullSrcs('documents/upingimg.jpg')}></Image>
                          <View className={styles['img_list_item_text']}>
                            <View className={styles['img_list_item_text_title']}>{fitem.name}</View>
                            <View className={styles['img_list_item_text_size']}>{fitem.size}</View>
                          </View>
                        </View>
                      )
                    })}
                  </View>
                  <Text className={styles['chat-item-ask-content']} selectable>
                    {item.content}
                  </Text>
                </View>
                {/* 回答 */}
                {item.children && item.children.length && (
                  <>
                    {item.children.map((child, childIndex) => {
                      return (
                        <View className={styles['chat-item-answer']} key={childIndex} id='msg-box'>
                          {childIndex === item.pageNo - 1 && (
                            <>
                              <Image className={styles['chat-item-img']} src={getFullSrcs('documents/zhongyou.png')} />
                              <View className={styles['chat-item-answer-content']}>
                                <View className={styles['chat-item-text-think']}>
                                  <View className={styles['chat-item-text- ']}>
                                    {item.children[item.pageNo - 1].thinking_enabled
                                      ? '思考中'
                                      : '已深度思考（用时' +
                                        item.children[item.pageNo - 1].thinking_elapsed_secs +
                                        '秒）'}
                                  </View>
                                  <View className={styles['chat-item-text-thinkContent']}>
                                    <RichText nodes={item.children[item.pageNo - 1].thinking_content}></RichText>
                                  </View>
                                </View>
                                {/* <View>{item.children[item.pageNo - 1].content}</View> */}

                                {item.children[item.pageNo - 1].content && (
                                  <towxml nodes={towxml(item.children[item.pageNo - 1].content, 'markdown')}></towxml>
                                )}
                                {!item.thinking_enabled && !timeOver && (
                                  <View className={styles['feedback-group']}>
                                    {item.children.length > 1 && (
                                      <View className={styles['history-index']}>
                                        <View
                                          onClick={() => {
                                            if (item.pageNo > 1) {
                                              setList((prevList) => {
                                                let flatprevList: any = [...prevList]
                                                let findex = flatprevList.findIndex((fitem, findx) => {
                                                  return fitem.message_id == item.message_id
                                                })
                                                flatprevList[findex] = {
                                                  ...flatprevList[findex],
                                                  pageNo: item.pageNo - 1
                                                }
                                                return flatprevList
                                              })
                                            }
                                          }}
                                        >
                                          ＜
                                        </View>
                                        <View>
                                          {item.pageNo}/{item.children.length}
                                        </View>
                                        <View
                                          onClick={() => {
                                            if (item.pageNo < item.children.length)
                                              setList((prevList) => {
                                                let flatprevList: any = [...prevList]
                                                let findex = flatprevList.findIndex((fitem, findx) => {
                                                  return fitem.message_id == item.message_id
                                                })
                                                flatprevList[findex] = {
                                                  ...flatprevList[findex],
                                                  pageNo: item.pageNo + 1
                                                }
                                                return flatprevList
                                              })
                                          }}
                                        >
                                          ＞
                                        </View>
                                      </View>
                                    )}
                                    {item.children[item.pageNo - 1].children.length === 0 && (
                                      <>
                                        <View
                                          className={styles['feedback-btn']}
                                          onClick={(e) =>
                                            handleCopy(
                                              item.children[item.pageNo - 1].content.replace(/<[^>]+>/g, ''),
                                              e
                                            )
                                          }
                                        >
                                          <Image
                                            className={styles['feedback-icon']}
                                            src='https://storage-backup001-001.jingxizhigu.cn/jxzg-park-service-ar/jncopy.png'
                                          />
                                        </View>
                                        <View
                                          className={styles['feedback-btn']}
                                          onClick={() => {
                                            console.log('refreshDatarefreshDatarefreshData', item.children)
                                            refreshData(item.children[item.pageNo - 1], item)
                                            // setTimeout(() => {
                                            //   setPageNo(item.children.length)
                                            // }, 1000)
                                          }}
                                        >
                                          <Image
                                            className={styles['feedback-icon']}
                                            src='https://storage-backup001-001.jingxizhigu.cn/jxzg-park-service-ar/jnrefresh.png'
                                          />
                                        </View>
                                        <View
                                          className={styles['feedback-btn']}
                                          onClick={(e) => handleFeedback('up', e, item.children[item.pageNo - 1])}
                                        >
                                          <Image
                                            className={styles['feedback-icon']}
                                            src={
                                              item.children[item.pageNo - 1].isSatisfied === true
                                                ? 'https://storage-backup001-001.jingxizhigu.cn/jxzg-park-service-ar/1339294140424392704.jpg'
                                                : 'https://storage-backup001-001.jingxizhigu.cn/jxzg-park-service-ar/jnup.png'
                                            }
                                          />
                                        </View>
                                        <View
                                          className={styles['feedback-btn']}
                                          onClick={(e) => handleFeedback('down', e, item.children[item.pageNo - 1])}
                                        >
                                          <Image
                                            className={styles['feedback-icon']}
                                            src={
                                              item.children[item.pageNo - 1].isSatisfied === false
                                                ? 'https://storage-backup001-001.jingxizhigu.cn/jxzg-park-service-ar/1339294237291843584.jpg'
                                                : 'https://storage-backup001-001.jingxizhigu.cn/jxzg-park-service-ar/jndown.png'
                                            }
                                          />
                                        </View>
                                      </>
                                    )}
                                  </View>
                                )}
                              </View>
                            </>
                          )}
                        </View>
                      )
                    })}
                  </>
                )}
              </View>
            )
          })}

          <View id='msg_last' className={styles['lastScroll']}></View>
          <View id='msg_last1' className={styles['lastScroll']}></View>
          {/* 弹窗功能 */}
          <PopFeedback ref={popRef} submitFun={submitFun}></PopFeedback>
          {/* 历史抽屉 */}
          <DrawerContent ref={drawerRef} clickItem={clickItem} delConfirm={delConfirm}></DrawerContent>
        </ScrollView>
        {isBottom && (
          <View className={styles['to_bottom']} onClick={toBottom}>
            <Image src='http://111.34.82.98:10001/talent/files/25bc3a06-aac8-4530-ab9e-41c2a3d54f92/zhankai.jpg'></Image>
          </View>
        )}
      </View>
      <View className={styles['bottomBtn']} style={{ bottom: bottom }}>
        <BottomBtn
          emitDataList={emitDataList}
          changeHeight={changeHeight}
          btnFun={btnFun}
          newChatFun={newChatFun}
          dataList={list}
          timeOver={timeOver}
          // 点加号叉号改变高度
          // changePhotosHeight={changePhotosHeight}
        />
      </View>
    </View>
  )
}
